import Vue from "vue";
import VueRouter from "vue-router";

import nprogress from "nprogress";

import { getToken } from "@/tools/auth";

import routes from "./router";

import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });

Vue.use(VueRouter);

// const BASE_URL = import.meta.env.BASE_URL;
const router = new VueRouter({
	base: "/",
	mode: "history",
	routes: [...routes],
	scrollBehavior: () => ({ y: 0 })
});

const BASE_TITLE = import.meta.env.APP_TITLE;

router.beforeEach((to, _from, next) => {
	document.title = `${BASE_TITLE} - ${to.meta.title}`;
	nprogress.start();
	const token = getToken();
	if (token) {
		if (to.path === "/login") {
			next({ path: "/" });
		} else {
			next();
		}
	} else {
		if (to.path !== "/login") {
			next({ path: "/login" });
		} else {
			next();
		}
	}
});

router.afterEach(() => {
	nprogress.done();
});

export default router;
